﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;

namespace System.Linq
{
	/// <summary>The SqlCacheDependencyGlobalNotifications class</summary>
	/// <created author="laurentiu.macovei" date="Sat, 03 Mar 2012 00:50:14 GMT"/>
	public static class SqlCacheDependencyGlobalNotifications
	{
		/// <summary></summary>
		/// <created author="laurentiu.macovei" date="Sat, 03 Mar 2012 00:50:14 GMT"/>
		public static event OnChangeEventHandler OnChange;

		/// <summary>
		/// Initialize SQL 2005/2008/2008R2+ push notifications for LINQ queries (including EntityFramework)
		/// </summary>
		/// <param name="connectString"></param>
		/// <created author="laurentiu.macovei" date="Sat, 03 Mar 2012 00:50:14 GMT"/>
			public static void InitializeNotifications(string connectString)
			{
				// Initialize notifications
				SqlDependency.Start(connectString);
				// Create and register a new dependency
				SqlDependency dependency = new SqlDependency();
				dependency.OnChange += new OnChangeEventHandler(NotificationCallback);
				System.Runtime.Remoting.Messaging.CallContext.SetData("MS.SqlDependencyCookie", dependency.Id);
			}

			/// <summary>
			/// </summary>
			/// <param name="o"></param>
			/// <param name="args"></param>
			/// <created author="laurentiu.macovei" date="Sat, 03 Mar 2012 00:50:15 GMT"/>
			internal static void NotificationCallback(object o, SqlNotificationEventArgs args)
			{
				OnChange.Invoke(o, args);
			}
	}
}
